using Vin.Extension.Win32.Command.Node;
using Vin.Extension.Win32.Command.Workflow;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Core.IntPtrCategory;
using Vin.Tool.Domain.ExceptionModel;
using Vin.Win32.Input;
using Win32.API;

namespace Vin.Extension.Win32.Command.Output;

/// <summary>
/// 发送文本到目标窗口（使用模拟输入）
/// </summary>
public class SendTextNode : BaseNode
{
    public override async Task ExecuteAsync(INodeContext context, IWorkflowContext workflowContext)
    {
        if (PrevFocusWindowHandle.IsNullOrZero())
        {
            throw new BusinessException("PrevFocusWindowHandle is null or zero");
        }

        if (Win32Api.SetForegroundWindow(PrevFocusWindowHandle))
        {
            await Task.Delay(100);
            var text = workflowContext.WorkflowData.GetResultValue;
            EmptyTool.CheckIsNull(text, "内容为空");
            VinKeyboardSimulator.Current.SendText(text!.ToString()!);
        }
        else
        {
            throw new BusinessException("SetForegroundWindow failed");
        }
    }

    public override void Dispose()
    {
    }
}